<template>
  <kennel
    :navList="navList"
    :navClass="'d-nav-bar-black'"
    :navActiveId="navActiveId"
    :isShowFooter="isShowFooter"
    :isLogin="isLogin"
    @login="handleLogin"
    @logout="handleLogout"
    ref="kennel">
    <template v-slot:header-side>
      <div class="d-header-side">
        <a class="d-text-link header-logo" :href="getMicroPath('#/')">
          <img class="d-img logo-image" src="../../assets/images/dog-logo-sm.png" />
          <span class="logo-text">{{ mappName }}</span>
        </a>
      </div>
    </template>
    <template v-slot:header-menu>
      <div class="d-header-menu"></div>
    </template>
    <template v-slot:layout-body>
      <div class="design-body d-layout-body d-bg-fog">
        <div class="design-render">
          <DRender ref="drender" />
        </div>
      </div>
    </template>
  </kennel>
</template>

<script>
import { mapState } from 'vuex'
import { Kennel } from '@daelui/vdog/dist/pages.js'
import { parser, treer } from '@daelui/dogjs/dist/components.js'
import uSer from '@/service/action/user.action.js'
import navSer from '@/service/action/nav.action'
import pageSer from '@/service/action/viewpage.action'
import ebus from '@/components/ebus'
import DRender from '@/views/dview/page/drender.vue'
import { setter } from '@/service/stock/index'
import componentCollection from '@/views/dview/page/components/components'
import vcSer from '@/service/action/viewcomp.action'

export default {
  components: {
    Kennel,
    DRender
  },

  computed: mapState({
    // 选中的导航id
    navActiveId: state => state.navActiveId
  }),

  data () {
    return {
      mappName: '微应用',
      navList: [],
      // 是否显示底部
      isShowFooter: false,
      // 是否登录
      isLogin: false
    }
  },

  watch: {
    '$route': function() {
      this.syncPage()
    }
  },

  created () {
    let params = this.$route.params
    if (params.id) {
      this.loadItem(params.id)
    }
  },

  beforeMount () {
    // 查询所有视图组件
    vcSer.queryAllComponents().then(cps => {
      componentCollection.push(...cps)
      setter.setComponentCollection(componentCollection)
    })
  },

  mounted () {
    // 登录完成
    ebus.$off('onLoginComplete')
    ebus.$on('onLoginComplete', () => {
      this.isLogin = true
    })
    // 超时
    ebus.$off('onLoginExpire')
    ebus.$on('onLoginExpire', () => {
      this.isLogin = false
    })
    // 获取用户信息
    uSer.queryUserInfo().then(res => {
      if (res && res.data && res.data.username) {
        ebus.$emit('onLoginComplete')
      }
    })
  },

  methods: {
    handleLogin () {
      // 弹出窗口
      ebus.$emit('onShowLogin')
    },
    handleLogout () {
      uSer.logout()
      this.isLogin = false
      // 清除token
      localStorage.removeItem('daelui-token')
    },
    /**
     * @function 加载数据
    */
    loadItem (id) {
      let rootPath = this.$route.path.replace(/(.*\/nav\/view\/[^\/]+).*/, '$1')
      navSer.queryItem({ id }).then(result => {
        let data = result.data || {}
        if (data.name) {
          this.mappName = data.name
          document.title = data.name
        }
        // 菜单处理
        let list = parser.parse(data.meta)
        list = Array.isArray(list) ? list : []
        list = this.solveMenu(list, rootPath, rootPath)
        console.log(list)
        this.navList = list
        let nodes = treer.treeToArray({ data: list })
        // 默认选中的菜单
        let defaultNav = null
        let query = this.$route.query
        if (query.pageId) {
          defaultNav = nodes.find(item => item.pageId === query.pageId)
        }
        if (!defaultNav) {
          defaultNav = nodes.find(item => item.isDefault)
        }
        if (!defaultNav) {
          defaultNav = nodes[0]
        }
        // 初始页面渲染
        if (defaultNav) {
          this.$store.state.navActiveId = defaultNav.id
          this.loadPage(defaultNav.pageId)
          // 初始化导航
          setTimeout(() => {
            this.$refs.kennel.handleChangeRoute(defaultNav.path)
          }, 300)
          if (defaultNav.name) {
            document.title = defaultNav.name
          }
        }
        // 路由处理
        list = this.solveRoute(list)
        console.log(list)
        list.forEach(item => {
          this.$router.addRoute('nav-view', item)
        })
      })
    },
    // 菜单解析
    solveMenu (list, parentPath, rootPath) {
      list = Array.isArray(list) ? list : []
      parentPath = parentPath || ''
      list.forEach(item => {
        item.text = item.name
        let path = item.pageId
        item.path = path
        item.url = '#' + parentPath + '?pageId=' + path
        item.match = item.pageId
        // 子级菜单
        if (item.children) {
          this.solveMenu(item.children, parentPath, rootPath)
        }
      })
      return list
    },
    // 路由解析
    solveRoute () {
      return []
    },
    // 页面渲染
    syncPage () {
      let query = this.$route.query
      if (query.pageId) {
        this.loadPage(query.pageId)
      }
      // 标题设置
      let nodes = treer.treeToArray({ data: this.navList })
      let node = nodes.find(item => item.pageId === query.pageId)
      if (node && node.name) {
        document.title = node.name
      }
    },
    // 加载页面
    loadPage (id) {
      pageSer.queryItem({ id }).then(result => {
        let data = result.data || {}
        // 组件元数据
        let meta = parser.parse(data.meta) || {
          component: 'div',
          properts: {},
          events: {},
          resource: {},
          theme: {},
          childComponents: []
        }
        meta.childComponents = meta.childComponents || []
        data.meta = meta
        this.$refs.drender.setPageState(data)
      })
    }
  }
}
</script>

<style lang="less">
.d-layout-header {
  position: relative;
  z-index: 5;
}
.design-render {
  width: 100%;
}
</style>
